/**
 * 
 */
package com.sofast.engine.parsepage.create;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sofast.bean.AlbumBean;
import com.sofast.bean.SongBean;
import com.sofast.bean.SongerBean;
import com.sofast.dao.AlbumDao;
import com.sofast.dao.SongDao;
import com.sofast.dao.SongerDao;
import com.sofast.engine.Spider;

/**
 * @author alex
 *
 */
public class SongerParse {
	
	private static String pathName = "J:\\WorkStudio\\images\\music_images\\";
	
	public SongerParse() {
		super();
	}

	public static List<SongerBean> parseSonger(String htmlString,String type){
		List<SongerBean> songerList = new ArrayList<SongerBean>();
		SongerDao songerDao = new SongerDao();
		char xChar = 'A';
		int start = 0;
		int end = 0;
		int j;
		int i = 1;
		while(xChar <= 'Z') {
			j = 1;
			start = htmlString.indexOf("\"initials_"+(char)xChar+"\"",start);
			if(start == -1) {
				start = 0;
				xChar ++;
				continue;
			}
			while((xChar+j) <= 'Z') {
				end = htmlString.indexOf("\"initials_"+(char)(xChar+j)+"\"",start);
				if(end != -1) {
					break;
				}
				j++;
			}
			
			if((xChar+j) > 'Z') {
				end = htmlString.length();
			}
			
			String zoneString = htmlString.substring(start, end);
			String reg = "<li(.*?)</li>";
			Pattern p = Pattern.compile(reg);
			Matcher m = p.matcher(zoneString);
			while(m.find()){
				SongerBean songer = new SongerBean();
				String liString = m.group(0);
				int ii = liString.indexOf("<a href=\"");
				int iii = liString.indexOf("\">",ii);
				songer.setUrl("http://www.1ting.com"+liString.substring(ii+9,iii));
				if(liString.indexOf("class=\"hot\"") != -1) {
					songer.setHot(1);
				}
				songer.setNameZone(type+"_"+xChar);
				songer.setName(liString.substring(liString.indexOf("html\">")+6,liString.indexOf("</a")));
				songer.setName(songer.getName().replaceAll("^.", ""));
				
				long id = songerDao.insert(songer);
				songer.setId(id);
				songerList.add(songer);
				
				// make new dir
				String fileName = pathName + songer.getId();
				File file = new File(fileName);
				file.mkdir();
				
				i++;
			}
			
			htmlString = htmlString.substring(start);
			start = 0;
			xChar ++;
		}
		return songerList;
	}
	
	public static List<SongerBean> parseBaidu(SongerBean songer,String name){
		String urlStr = "http://mp3.baidu.com/singerlist/"+encode(songer.getName())+".html";
		Spider spider = new Spider(urlStr,"gbk");
		String htmlString = spider.getHtmlString();
		AlbumDao albumDao = new AlbumDao();
		int start;
		int end = 0;
		
		/*
		 // parse the songer image url
		start = htmlString.indexOf("<div class=\"box\" id=\"singer\">");
		start = htmlString.indexOf("<img src=\"", start);
		start += 10;
		end = htmlString.indexOf("\"",start);
		String imageURL = htmlString.substring(start,end);
		//*/
		System.out.println(songer.getNameZone()+" : "+songer.getName());
		while(true) {
			start = htmlString.indexOf("<div class=\"album\">",0);
			if(start == -1) {
				break;
			}
			end = htmlString.indexOf("<div class=\"album\">",start+21);
			if(end == -1) {
				end = htmlString.length();
			}
			
			String albumString = htmlString.substring(start, end);
			AlbumBean album = parseAlbum(albumString,songer);
			
			// insert into album db
			long id = albumDao.insert(album);
			album.setId(id);
			
			// get the song list
			String songsString = albumString.substring(albumString.indexOf("<table class=\"songlist")+22, 
					albumString.indexOf("</table>"));
			parseSong(songsString, album);

			// download the albumn image
			int ii = albumString.indexOf("<img src=\"", 0);
			int iii = albumString.indexOf("\"", ii+10);
			String imageURL = "";
			if(ii != -1)
				imageURL = albumString.substring(ii+10,iii);
			if(!imageURL.equalsIgnoreCase("http://imgs.zhangmen.baidu.com/mp3index/mlist/img/no.gif") && ii != -1) {
				Spider.downloadImgae(imageURL, pathName+album.getSonger().getId()+"/"+album.getId()+".jpg");
			}
			
			htmlString = htmlString.substring(end);
		}
		 
		
		return null;
	}
	
	private static void parseSong(String songsString, AlbumBean album) {
		SongDao songDao = new SongDao();
		while(true) {
			// get the song name
			int iis = songsString.indexOf("title=\"");
			if(iis == -1 ) {
				break;
			}
			int iiis = songsString.indexOf("\">", iis);
			String songName = "";
			songName = songsString.substring(iis+7, iiis);
			
			SongBean song = new SongBean();
			song.setAlbum(album);
			song.setName(songName);
			song.setSonger(album.getSonger());
			album.getSongList().add(song);
			
			// insert into song db
			songDao.insert(song);
			
			songsString = songsString.substring(iiis);
		}
	}
	
	private static AlbumBean parseAlbum(String htmlString,SongerBean songer) {
		AlbumBean album = new AlbumBean();
		album.setSonger(songer);
		DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat df2 = new SimpleDateFormat("yyyy-MM");
		DateFormat df3 = new SimpleDateFormat("yyyy");
		
		// get the albumn name
		int ii = htmlString.indexOf("title=\"", 0);
		int iii = htmlString.indexOf("\">", ii);
		album.setName(htmlString.substring(ii+7, iii));

		// get the publish time 
		ii = htmlString.indexOf("发行时间:", 0);
		iii = htmlString.indexOf("<br",ii+5);
		if(ii != -1) {
			ii += 5;
			String timeStr = htmlString.substring(ii, iii);
			timeStr = timeStr.trim();
			if(!"".equals(timeStr)) {
				try {
					switch (timeStr.length()) {
						case 4:
							album.setPublishTime(df3.parse(timeStr).getTime());				
							break;
						case 7:
							album.setPublishTime(df2.parse(timeStr).getTime());
							break;
						case 10:
							album.setPublishTime(df1.parse(timeStr).getTime());
							break;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
		
		// get the company name
		ii = htmlString.indexOf("唱片公司:", 0);
		iii = htmlString.indexOf("</p>",ii+5);
		if(ii != -1) {
			ii += 5;
			String companyString = htmlString.substring(ii,iii);
			companyString = companyString.trim();
			album.setComp(companyString);
		}
		
		return album;
	}
	
	private static String encode(String str)
    {
	     String s=str;
	     try {
			s = URLEncoder.encode(str, "gb2312");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	     return s;
   }
	
	private boolean isChinese(String str) {
		return (str.getBytes().length == str.length());
	}
	
	public static void main(String[] args) {
		String url = "http://www.1ting.com/group/group0_1.html";
		Spider spider = new Spider(url,"utf-8");
		
		//SongerParse.parseSonger(spider.getHtmlString());
		
		SongerBean songer = new SongerBean();
		songer.setName("林俊杰");
		SongerParse.parseBaidu(songer,"1");
	}

}
